package com.fansl.allround.upms.helper.region;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.fansl.allround.common.core.constant.enums.RegionLevelEnum;
import com.fansl.allround.upms.api.entity.SysRegion;
import com.fansl.allround.upms.service.SysRegionService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import us.codecraft.webmagic.ResultItems;
import us.codecraft.webmagic.Task;
import us.codecraft.webmagic.pipeline.Pipeline;

import java.util.List;

import static com.fansl.allround.upms.helper.RegionHelper.HELP_URL;
import static com.fansl.allround.upms.helper.RegionHelper.PREFIX_REGION_HELP_URL_KEY_IN_REDIS;

/**
 * @author fansl
 * @Description: 存入数据库
 * @date 2019/8/27 10:32
 */
@Slf4j
@AllArgsConstructor
public class RegionPipeline implements Pipeline {
    private final SysRegionService sysRegionService;

    private final RedisTemplate redisTemplate;

    @Override
    public void process(ResultItems resultItems, Task task) {

        String helpUrl = resultItems.get(HELP_URL).toString();
        resultItems.getAll().forEach((key, value) -> {
            if (!key.equals(HELP_URL)) {
                RegionLevelEnum regionLevelEnum = RegionLevelEnum.valueOf(key);
                switch (regionLevelEnum) {
                    case PROVINCE:
                    case CITY:
                    case COUNTY:
                    case TOWN:
                    case VILLAGE:
                        if (null != value) {
                            List<SysRegion> sysRegionList = JSONArray.parseArray(JSON.toJSONString(value), SysRegion.class);
                            if (sysRegionList.isEmpty()) {
                                log.warn("区域信息为空，helpUrl:{}", helpUrl);
                                return;
                            }
                            boolean result = sysRegionService.saveBatch(sysRegionList);
                            log.info("获取{}数量：{}，新增结果：{}", key, sysRegionList.size(), result);
                            if (StrUtil.isNotBlank(helpUrl)) {
                                String redisKey = PREFIX_REGION_HELP_URL_KEY_IN_REDIS + regionLevelEnum.getLevel();
                                Long count = redisTemplate.opsForSet().remove(redisKey, helpUrl);
                                log.info("移除引导页,redisKey:{},value:{},result:{}", redisKey, helpUrl, count);
                            }
                        }
                        return;
                    default: {
                        return;
                    }
                }
            }
        });
    }
}
